package com.simtop.controller;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.dao.CountDao;
import com.simtop.pojo.*;
import com.simtop.pojo.SuccessVo;
import com.simtop.pojo.wddata.WdDate;
import com.simtop.pojo.wddata.swWdDate;
import com.simtop.service.ApiService;
import com.simtop.service.JwtLoginService;
import com.simtop.service.UserService;
import com.simtop.util.IlabUtil;
import com.simtop.util.JwtUtil;
import com.simtop.util.SHA256Util;
import com.simtop.util.excel.ExcelUtils;
import com.simtop.vo.*;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


import java.util.ArrayList;
import java.util.List;


/**
 * 用户模块
 */
@Controller
@RequestMapping("/user")
@CrossOrigin //todo 跨域问题
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JwtLoginService jwtLoginService;

    @Autowired
    private CountDao countDao;

    @Autowired
    private IlabUtil ilabUtil;

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private ApiService apiService;

    /**
     * 前台用户注册接口
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(UserVoS userVoS, MultipartFile file ,HttpServletRequest request)  {
        try{
            //     System.out.println("接收到的前台参数为：" + userVo);
            // System.out.println(file.getName());
            // System.out.println(file.getOriginalFilename());
            //File uploadfile=new File("C:\\webProject\\Java\\swimage\\" + userVoS.getUserName() + file.getOriginalFilename());
            //File uploadfile = new File("C:\\Users\\Administrator\\Desktop\\sw\\" + userVoS.getUserName() + file.getOriginalFilename());
            File uploadfile = new File("C:\\webProject\\Java\\swimage\\" + userVoS.getUserName() + file.getOriginalFilename());

            String asa = "http://82.156.232.217/swimage/"+ userVoS.getUserName() + file.getOriginalFilename();
            //String asa = "http://192.168.0.113/sw/" + userVoS.getUserName() + file.getOriginalFilename();
            //  System.out.println(file.getResource());
            try {
                file.transferTo(uploadfile);

            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e);
            }

            return userService.register(userVoS, asa);
        }
        catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByError();

        }
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     *
     * @return
     */
    @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(String email) {
        //根据邮箱获取验证码
        return userService.generateCheckCode(email);
    }

    /**
     * ilab平台用户登陆 2019年10月11日15:50:32
     */
    @RequestMapping(value = "/ilab/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody IlabUser ilabUser, HttpServletRequest request) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("获取到的ilab参数token为：" + ilabUser.getToken());
        //获取ilab传递过来的token
        String token = ilabUser.getToken();
        try {
            /**
             * 调用ilab接口获取用户信息
             */
            String ilabJson = ilabUtil.getAccessToken(token);
            JSONObject o = JSONObject.parseObject(ilabJson);
            int code = o.getInteger("code");
            /**
             * 判断code不为0,则从ilab获取内容失败
             */
            if (code != 0) {
                return ServerResponse.createByErrorMsg("token失效，请重新通过ilab进入重做实验");
            }
            String loginName = o.getString("un");
            String username = o.getString("dis");
            //如果数据库存在登陆用户名 则直接返回
            User user = userService.selectUserByLoginName(loginName);
            if (user != null) {
                user.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
                String token1 = JwtUtil.sign(user, 60L * 1000L * 60L * 24);//token有效期24小时
                /**
                 * todo 统计网站访问次数：登陆成功后统计次数变量count加1
                 */
                int num = countDao.selectCount();
                int count = ++num;
                countDao.updateOne(count);
                return ServerResponse.createBySuccess(token1);
            }
            //不存在则在用户数据表中创建用户数据
            UserVo userVo = new UserVo();
            userVo.setLoginName(loginName);
            userVo.setUsername(username);
            //ilab用户身份
            userVo.setRoleId(5);
            userVo.setPassword(SHA256Util.generateShaPwd("12345"));
            int resultCount = userService.insertIlabUser(userVo);
            //插入用户数据 给前端返回user的jwt对象
            User u = userService.selectUserByLoginName(userVo.getLoginName());
            //将access_token放入用户对象生成token
            u.setAccessToken(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
            System.out.println(URLEncoder.encode(o.getString("access_token"), "UTF-8"));
            //24小时的token有效期
            String token1 = JwtUtil.sign(u, 60 * 60 * 1000 * 24L);
            int num = countDao.selectCount();
            int count = ++num;
            countDao.updateOne(count);
            return ServerResponse.createBySuccess(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMsg("新增ilab平台用户失败");
    }

    /**
     * 用户登录 成功后给前台返回一个token,后面需要拿这个token去验证
     * todo 用户类型：ilab用户 2019年9月24日15:34:07
     * 前台传入
     *
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public SuccessVo login(@RequestBody UserVo userVo, HttpServletResponse response) {

            User user = new User();
            //登录名
            user.setLoginName(userVo.getLoginName());
            //登陆密码
            user.setPassword(userVo.getPassword());
            return jwtLoginService.login(user);

    }


    @RequestMapping(value = "/findAllList", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse findAllList(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer pageNum = jsonObject.getInteger("pageNum");
            Integer pageSize = jsonObject.getInteger("pageSize");

            if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
                pageNum = 1;
            }
            if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNum, pageSize);

            String tameName = jsonObject.getString("tameName");
            String userName = jsonObject.getString("userName");



            List<UserVoS> findAllLayOut = userService.findAllList(tameName,userName);
            PageInfo<UserVoS> pageInfo = new PageInfo<UserVoS>(findAllLayOut);


            return ServerResponse.createBySuccess("获取内容成功", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    @RequestMapping(value = "/lxuser", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse lxuser( HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        try {
            Integer id = u.getId();

            apiService.changeUser(id);


            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }


    //村表
    @RequestMapping(value = "/savefindAllList", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse savefindAllList(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        Integer coach=u.getId();
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String type = jsonObject.getString("type");
            String userlist = jsonObject.getString("userlist");
            List<swWdDate> lastDate = JSON.parseArray(userlist, swWdDate.class);
            List<YongdaoPo> yongdaoPoList = new ArrayList<YongdaoPo>();
            for (swWdDate as:lastDate
                 ) {
                Integer userId = as.getUserId();
                int a  = apiService.getOne(userId);

                if(a>0){
                    continue;
                }


                int i  = 1;
                int j = i ++ ;
                YongdaoPo yongdaoPo = new YongdaoPo();
                yongdaoPo.setUsername(as.getUserName());
                yongdaoPo.setUserteam(as.getTameName());
                yongdaoPo.setSwtype(type);
                yongdaoPo.setUserids(String.valueOf(j));
                yongdaoPo.setUserid(String.valueOf(as.getUserId()));
                yongdaoPo.setSwstatus(1);
                yongdaoPo.setCoach(coach);


                yongdaoPoList.add(yongdaoPo);

            }
            apiService.insertYongdao(yongdaoPoList);

            //查询所有的数据



            List<SwyDone> sa = apiService.findAllSwyDone();

            return ServerResponse.createBySuccess("获取内容成功",sa);
        } catch (Exception e) {
            e.printStackTrace();
            List<SwyDone> sa = apiService.findAllSwyDone();

            return ServerResponse.createBySuccess("获取内容成功",sa);
        }
    }



    @RequestMapping(value = "/findAllList2", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse findAllList2(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer pageNum = jsonObject.getInteger("pageNum");
            Integer pageSize = jsonObject.getInteger("pageSize");

            if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
                pageNum = 1;
            }
            if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNum, pageSize);

            String tameName = jsonObject.getString("tameName");



            List<UserVoS> findAllLayOut = userService.findAllList2(tameName);
            PageInfo<UserVoS> pageInfo = new PageInfo<UserVoS>(findAllLayOut);


            return ServerResponse.createBySuccess("获取内容成功", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }


    @RequestMapping(value = "/findAllListTeam", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse findAllListTeam(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        try {
         List<TeamType> teamTypes = userService.findAllListTeam();

            return ServerResponse.createBySuccess(teamTypes);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    @RequestMapping(value = "/insertAllListTeam", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse insertAllListTeam(@RequestBody String data,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String teamName = jsonObject.getString("teamName");
            userService.insertAllListTeam(teamName);


            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("团队名称重复");
        }
    }

    @RequestMapping(value = "/deleteAllListTeam", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse deleteAllListTeam(@RequestBody String data,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer id = jsonObject.getInteger("id");

            int count = userService.finOnly(id);
            if(count>0){

                return ServerResponse.createByErrorMsg("请先删除队内所有人员");
            }

            userService.deleteAllListTeam(id);


            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    @RequestMapping(value = "/updateAllListTeam", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse updateAllListTeam(@RequestBody String data,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }


        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer id = jsonObject.getInteger("id");
            String teamName = jsonObject.getString("teamName");

            userService.updateAllListTeam(id,teamName);

            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    @PostMapping("/deletefindAllList")
    @ResponseBody
    public ServerResponse deletefindAllList(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        String id = jsonObject.getString("id");
        String[] split = id.split(",");
        ArrayList<Integer> sqsyidlist = new ArrayList<>();


        Iterator<String> iterator = Arrays.stream(split).iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            Integer i = Integer.valueOf(next);
            sqsyidlist.add(i);

            // apiService.finOne
        }
        userService.deletefindAllList(sqsyidlist);
        return ServerResponse.createBySuccess();
    }

    //删除文件和目录
    private void clearFiles(String workspaceRootPath) {
        File file = new File(workspaceRootPath);
        if (file.exists()) {
            deleteFile(file);
        }
    }

    private void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFile(files[i]);
            }
        }
        file.delete();
    }



        /**复制文件的方法*/
        public static void copyFile(String oldPath, String newPath) {
            try {
                int bytesum = 0;
                int byteread = 0;
                File oldfile = new File(oldPath);
                if (oldfile.exists()) { //文件存在时
                    InputStream inStream = new FileInputStream(oldPath); //读入原文件
                    FileOutputStream fs = new FileOutputStream(newPath);
                    byte[] buffer = new byte[1444];
                    while ( (byteread = inStream.read(buffer)) != -1) {
                        bytesum += byteread; //字节数 文件大小
                        fs.write(buffer, 0, byteread);
                    }
                    inStream.close();
                    fs.close();
                }
            }
            catch (Exception e) {
                System.out.println("复制单个文件操作出错");
                e.printStackTrace();
            }
        }







    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();

            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除

        return dir.delete();
    }


    public static String consumeInputStream(InputStream is) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String s;
        StringBuilder sb = new StringBuilder();
        while ((s = br.readLine()) != null) {
            System.out.println(s);
            sb.append(s);
        }
        System.out.println("执行结束");
        return sb.toString();
    }

    @RequestMapping(value = "/readcsv", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<Total> readcsv(String csvpath) {
            if(csvpath.endsWith(".xlsx")){
                try {
                    Total total = new Total();
                    ArrayList<Object> objects = new ArrayList<>();
                    ArrayList<Object> objects2 = new ArrayList<>();
                    ArrayList<Object> objects3 = new ArrayList<>();
                    //创建工作簿
                    XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(csvpath));
                    //System.out.println("xssfWorkbook对象：" + xssfWorkbook);
                    //读取第一个工作表
                    XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
                    //System.out.println("sheet对象：" + sheet);
                    int maxRow = sheet.getLastRowNum();
                    //System.out.println("总行数为：" + maxRow);
                    for (int row = 0; row <= maxRow; row++) {


                        //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                        int maxRol = sheet.getRow(row).getLastCellNum();
                        //System.out.println("--------第" + row + "行的数据如下--------");
                        for (int rol = 0; rol < maxRol; rol++){
                            if(sheet.getRow(row).getCell(rol) ==null){
                                continue;

                            }
//                    System.out.print(sheet.getRow(row).getCell(rol) + "  ");
                            objects.add(sheet.getRow(row).getCell(rol).toString());

                        }


//                System.out.println();
                        objects2.add(objects);
                    }


                    total.setOs(objects2);
                    total.setTo(objects2.size());
                    return ServerResponse.createBySuccess(total);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return ServerResponse.createByError();
            }



    String csvFile = csvpath;
    String line = "";
    String cvsSplitBy = ",";

    ArrayList<Object> objects = new ArrayList<>();
    ArrayList<Object> objects2 = new ArrayList<>();
    Total total = new Total();
    DataInputStream in = null;
    try {
        in = new DataInputStream(new FileInputStream(new File(csvFile)));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try (BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {

        while ((line = br.readLine()) != null) {
            // use comma as separator
            String[] country = line.split(cvsSplitBy);

            objects.add(country);

        }
        System.out.println(objects.size());
        if (objects.size() > 2000) {
            for (int i = 0; i < 1001; i++) {
                Object o = objects.get(i);
                objects2.add(o);
            }
            total.setOs(objects2);
            total.setTo(objects.size());
            return ServerResponse.createBySuccess(total);

        }

        total.setOs(objects);
        total.setTo(objects.size());
        return ServerResponse.createBySuccess(total);

    } catch (IOException e) {
        e.printStackTrace();
    }



        return ServerResponse.createByError();
    }

    //判断文件格式
    private static Workbook readExcel(String filePath) {
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));

        try {
            @SuppressWarnings("resource")
            InputStream is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return new XSSFWorkbook(is);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;


    }

    /**
     * 游客登录
     *
     * @return
     */
    @PostMapping("/tourist")
    @ResponseBody
    public SuccessVo tourist() {
        UserVo loginUser = new UserVo();
        String s = UUID.randomUUID().toString();
        loginUser.setLoginName(s);
        loginUser.setUsername("评审专家");
        loginUser.setRoleId(3);
        loginUser.setPassword("JGL_tourist");
        userService.insertBackUser(loginUser);
        User user = new User();
        //角色id
        user.setRoleId(3);
        //登录名
        user.setLoginName(s);
        //登陆密码
        user.setPassword("JGL_tourist");
        return jwtLoginService.login(user);

    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     */
    @RequestMapping(value = "/forget_checkCode", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(email);
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody UserVo userVo) {
        return userService.updatePassword(userVo);
    }

    /**
     * 用户管理 查看所有的数据
     */
    @RequestMapping(value = "/backend/findAll", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findAll(HttpServletRequest request, Integer pageNum, Integer pageSize, String school) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        if (ObjectUtils.isEmpty(pageNum)) {
            pageNum = 1;
        }
        if (ObjectUtils.isEmpty(pageSize)) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        User user = new User();
        user.setRoleId(u.getRoleId());
        System.out.println(user);
        List<User> userList = userService.findAll(user);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 用户管理 权限查看
     */
    @RequestMapping(value = "/backend/findAlls", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findAlls(HttpServletRequest request, Integer pageNum, Integer pageSize) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        if (ObjectUtils.isEmpty(pageNum)) {
            pageNum = 1;
        }
        if (ObjectUtils.isEmpty(pageSize)) {
            pageSize = 10;
        }
        if(!(u.getRoleId() == 1) && !(u.getRoleId() == 2)){
            return ServerResponse.createByErrorMsg("无权限");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userService.findAlls();
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 新增后台用户管理记录
     */
    @RequestMapping(value = "/backend/add", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> addUser(@RequestBody UserVo userVo, Integer userId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.insertBackUser(userVo);
    }

    /**
     * 根据用户id删除User表数据
     */
    @RequestMapping(value = "/deleteByUserId", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> deleteById(@RequestBody String data, HttpServletRequest request) {
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        Integer userId = jsonObject.getInteger("userId");
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        logger.info("管理员删除用户,编号为{}", userId);
        return userService.deleteByUserId(userId);
    }

    @RequestMapping(value = "/backend/update", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updateBackendUser(UserVoS userVo,MultipartFile file, HttpServletRequest request,int status) {

        if(status ==  1) {
            //File uploadfile = new File("C:\\Users\\Administrator\\Desktop\\asa\\" + userVo.getUserName() + file.getOriginalFilename());
            File uploadfile = new File("C:\\Users\\Administrator\\Desktop\\sw\\" + userVo.getUserName() + file.getOriginalFilename());

            try {

                file.transferTo(uploadfile);

                //String asa = "http://192.168.0.113/sw/"+ userVo.getUserName() + file.getOriginalFilename();
                String asa = "http://192.168.0.113/sw/"+ userVo.getUserName() + file.getOriginalFilename();

                System.out.println(file.getResource());
                System.out.println(status);

                return userService.updateBackendUser(userVo,asa,status);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        String asa = "http://82.156.232.217/swimage/login.jpg";
        return userService.updateBackendUser(userVo,asa,status);


    }


    @RequestMapping(value = "/backend/findtam", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse findtam(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }

        //获取所有团队
        List<TeamType> teamTypes =  userService.findtam();



        return  ServerResponse.createBySuccess(teamTypes);
    }

    /**
     * 根据用户id查询用户信息
     */
    @RequestMapping(value = "/backend/findById", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<User> findUserById(HttpServletRequest request, Integer id) {
        String token = request.getHeader("Authorization");
        if (token == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.findById(id);
    }

    /**
     * 用户查询功能(学校、姓名、登录名查询)
     */
    @RequestMapping(value = "/backend/findByParams", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findByParams(HttpServletRequest request, UserParamsVo params, Integer pageNum, Integer pageSize) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }

        params.setRoleId(u.getRoleId());
        params.setUserId(u.getId());
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userService.findByParams(params);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 获取模板
     */
    @GetMapping("/getUserTemplate")
    public void getUserTemplate(HttpServletRequest request, HttpServletResponse response) {
        excelUtils.cooperation(request, response, User.class, "上传用户模板");
    }

    /**
     * 上传接口
     */
    @PostMapping("/importUser")
    @ResponseBody
    public ServerResponse<Object> importUsers(MultipartFile file) {
        List<Object> upload = excelUtils.upload(file, User.class);
        return userService.importUsers(upload);
    }
    @RequestMapping(value = "/testExcel", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<Total> testExcel(String csvpath) {
        File xlsFile = new File(csvpath);

        // 工作表
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(xlsFile);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 表个数。
        int numberOfSheets = workbook.getNumberOfSheets();

        // 遍历表。
        for (int i = 0; i < numberOfSheets; i++) {
            Sheet sheet = workbook.getSheetAt(i);

            // 行数。
            int rowNumbers = sheet.getLastRowNum() + 1;

            // Excel第一行。
            Row temp = sheet.getRow(0);
            if (temp == null) {
                continue;
            }

            int cells = temp.getPhysicalNumberOfCells();

            // 读数据。
            for (int row = 0; row < rowNumbers; row++) {
                Row r = sheet.getRow(row);
                for (int col = 0; col < cells; col++) {
                    if (r.getCell(col) == null) {
                        continue;
                    }

                    System.out.print(r.getCell(col).toString()+" ");
                }

                // 换行。
                System.out.println();
            }
        }

return ServerResponse.createByError();
    }


    @RequestMapping(value = "/testExcel2", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<Total> testExcel2(String csvpath) {
        try {
            Total total = new Total();
            ArrayList<Object> objects2 = new ArrayList<>();

            //创建工作簿
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(csvpath));
            //System.out.println("xssfWorkbook对象：" + xssfWorkbook);
            //读取第一个工作表
            XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
            //System.out.println("sheet对象：" + sheet);
            int maxRow = sheet.getLastRowNum();
            //System.out.println("总行数为：" + maxRow);
            for (int row = 0; row <= maxRow; row++) {
                ArrayList<Object> objects = new ArrayList<>();

                //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                int maxRol = sheet.getRow(row).getLastCellNum();
                //System.out.println("--------第" + row + "行的数据如下--------");
                for (int rol = 0; rol < maxRol; rol++){
                    if(sheet.getRow(row).getCell(rol) ==null){
                        continue;

                    }
//                    System.out.print(sheet.getRow(row).getCell(rol) + "  ");
                    objects.add(sheet.getRow(row).getCell(rol).toString());
                }
                objects2.add(objects);

//                System.out.println();
            }

            total.setOs(objects2);
            total.setTo(objects2.size());
            return ServerResponse.createBySuccess(total);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ServerResponse.createByError();
    }

    /***
     * 用户退出时改退出最后一次登录时间
     */
    @RequestMapping(value = "/updateLastTime")
    @ResponseBody
    public ServerResponse updateLastTime(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            Integer Id=u.getId();
            userService.updateLastTime(Id);
            return ServerResponse.createBySuccess();
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("退出失败");
        }
    }
}